<?php
class MUploadCtl extends BaseCtl {
	public function MUploadCtl(){
		parent::BaseCtl();
	}
	
    public function isPostback(){
    	return 'mupload' == $this->getPost('pagename');
    }
    
    public function loadData(){
    	// no implementation
    }
    
    public function submit(){
    	try {
    		$form = $this->getMUploadForm();
    		$frm = $this->getPicturesForm();
    		
    		
    		$albumId = $form->getAlbumId();
    		    		
    		$service = new Service();
    		
    		if(array_key_exists('picturefile', $_FILES)){
    			$files = $_FILES['picturefile'];
    			
    			// ok, processing the files
    			// the files are collection of arrays
    			$nr = count($files['name']); // get the first item
    			
    			
    			for($i = 0; $i < $nr; $i ++){
    				$fl = $this->getFile($files, $i);
    				$service = new Service();
    				
    				$id = $service->getNewId();
    				$comments = ''; // for automatic adding, no comments
    				
    				if($this->processFile($fl, $id)){
    					$picture = new Picture();
    					
    					$picture->setAlbumId($albumId);
    					$picture->setComments($comments);
    					$picture->setId($id);
    					$picture->setSeqNo($service->getMaxPictureSeq() + 10);
    					
    					$service->addPicture($picture);
    					
    					// after adding, will add the result to the pictures form
    					$frm->addPicture($picture);
    				}
    				else { 
    					HtmlUtil::addError('could not process file: ' . $i );
    				}
    			}
    			
    			HtmlUtil::addMessage("OK, files uploaded, please upload some more or click Cancel to go back to pictures page");
    		}
    		else {
    			HtmlUtil::addError("Please select at least one file and resubmit");
    		}
    	}
    	catch(Exception $e){
    		HtmlUtil::addError($e->getMessage());
    	}
    }
    
    private function getFile($files, $i){
    	$arr = array();
    	
    	foreach($files as $key => $value){
    		$arr[$key] = $files[$key][$i];
    	}
    	
    	return $arr;
    }
    
    public function cancel(){
    	try {
    		$this->redirect('pictures.php');
    	}
    	catch(Exception $e){
    		HtmlUtil::addError($e->getMessage());
    	}
    	
    }
} 
?>